package org.zhaya.sdk.processors.condition;

import io.logz.sawmill.Condition;
import io.logz.sawmill.Doc;
import io.logz.sawmill.annotations.ConditionProvider;
import io.logz.sawmill.parser.ConditionParser;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@ConditionProvider(type = "notExist", factory = FieldNotExistCondition.Factory.class)
public class FieldNotExistCondition implements Condition {
    private final String field;

    public FieldNotExistCondition(String field) {
        this.field = field;
    }

    @Override
    public boolean evaluate(Doc doc) {
        boolean flag = doc.hasField(this.field);
        if (flag) {
            flag = false;
            Object value = doc.getField(this.field);
            if (value == null) {
                flag = true;
            }
            if ((value instanceof List)) {
                if (((List) value).size() == 0) {
                    flag = true;
                }
            }
            if ((value instanceof String)) {
                if (StringUtils.isBlank((String) value)) {
                    flag = true;
                }
            }
        } else {
            flag = true;
        }
        return flag;
    }

    public static class Factory implements Condition.Factory {

        @Override
        public Condition create(Map<String, Object> config, ConditionParser conditionParser) {
            Configuration existsCondition = JsonUtils.fromJsonMap(Configuration.class, config);

            return new FieldNotExistCondition(existsCondition.getField());
        }
    }

    @Data
    public static class Configuration {
        private String field;

    }
}